﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 汉字与Unicode转换
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string str = tbSrc.Text.Trim();
            if(str.Length < 1)
            {
                Console.WriteLine("请输入汉字");
            }
            else
            {
                //string srcStr = str.Substring(0, 1);
                //Console.WriteLine($"srcStr:{srcStr}");
                lbResult1.Text = CharacterToCoding(str);
            }
        }

        /// <summary>
        /// 将 character 字符串 转换成 unicode字符串
        /// </summary>
        /// <param name="character"></param>
        /// <returns></returns>
        public string CharacterToCoding(string character)
        {
            string coding = "";
            for (int i = 0; i < character.Length; i++)
            {
                byte[] bytes = Encoding.Unicode.GetBytes(character.Substring(i, 1));

                //取出二进制编码内容 
                string lowCode = Convert.ToString(bytes[0], 16);

                //取出低字节编码内容（两位16进制） 
                if (lowCode.Length == 1)
                {
                    lowCode = "0" + lowCode;
                }

                string hightCode = Convert.ToString(bytes[1], 16);

                //取出高字节编码内容（两位16进制） 
                if (hightCode.Length == 1)
                {
                    hightCode = "0" + hightCode;
                }

                coding += (hightCode + lowCode);
            }
            return coding;
        }


        /// <summary>
        /// 将 unicode字符串 转换成  正常的字符串 
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string UnicodeToCharacter(string text)
        {
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < text.Length; i += 4)
            {
                var chStr = ((char)int.Parse(text.Substring(i, 4), System.Globalization.NumberStyles.HexNumber)).ToString();
                sb.Append(chStr);
            }
            return sb.ToString();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            string unicodeStr = lbResult1.Text.Trim();
            if(unicodeStr.Length < 1)
            {
                Console.WriteLine("unicode字符串为空!");
            }
            else
            {
                lbResult2.Text = UnicodeToCharacter(unicodeStr);
            }
        }
    }


}
